using System;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Logging;
using MySql.Data.MySqlClient;

namespace ManaMaple.Core.HealthChecks
{
    public class DatabaseHealthCheck : IHealthCheck
    {
        private readonly IConfiguration _configuration;
        private readonly ILogger<DatabaseHealthCheck> _logger;
        private readonly string _connection;

        public DatabaseHealthCheck(IConfiguration configuration, ILogger<DatabaseHealthCheck> logger)
        {
            _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            
            // 使用null条件运算符和默认值，避免null引用警告
            var connStr = _configuration.GetConnectionString("mysql");
            _connection = !string.IsNullOrEmpty(connStr) 
                ? connStr 
                : throw new InvalidOperationException("数据库连接字符串'mysql'未配置");
        }

        public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                using (var connection = new MySqlConnection(_connection))
                {
                    _logger.LogInformation("开始检查数据库连接健康状态");
                    await connection.OpenAsync(cancellationToken);

                    using (var command = connection.CreateCommand())
                    {
                        command.CommandText = "SELECT 1";
                        await command.ExecuteScalarAsync(cancellationToken);
                    }

                    _logger.LogInformation("数据库连接健康检查成功");
                    return HealthCheckResult.Healthy("数据库连接正常");
                }
            }
            catch (DbException ex)
            {
                _logger.LogError(ex, "数据库连接健康检查失败");
                return HealthCheckResult.Unhealthy("数据库连接异常", ex);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "数据库连接健康检查过程中发生未知错误");
                return HealthCheckResult.Unhealthy("健康检查过程中发生未知错误", ex);
            }
        }
    }
}